package com.wufun.overseas.main.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.wufun.overseas.tools.socket.entity.SocketConfig;
import com.wufun.overseas.tools.socket.entity.SocketStatusEvent;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Author: hest
 * Date:  2016/5/26
 * Socket 服务端Service
 */
public class SocketServerService extends Service {
    private static final String TAG = SocketServerService.class.getSimpleName();
    private SocketBinder mBinder = new SocketBinder();

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: ");
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind: ");
        return mBinder;
    }

    @Override
    public void onRebind(Intent intent) {
        Log.d(TAG, "onRebind: ");
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "onUnbind: ");
        return true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
        releaseSocket();
    }


    void releaseSocket(){
        if(mBinder==null){
            return;
        }

        if(mBinder.mSocketService!=null&&!mBinder.mSocketService.isClosed()){
            try {
                mBinder.mSocketService.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(mBinder.mSocket!=null&&!mBinder.mSocket.isClosed()){
            try {
                mBinder.mSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public class SocketBinder extends Binder {
        private ServerSocket mSocketService;
        private boolean mointor = true;
        private Socket mSocket=null;

        public void newServerSocket() {
            try {
                Log.d(TAG, "newServerSocket: ");
                mSocketService = new ServerSocket();
                //mSocketService.setSoTimeout(SocketConfig.SOCKETSERVER_CONNECTED_TIME_OUT);
                mSocketService.setReceiveBufferSize(SocketConfig.TCP_BUFFER_SIZE);
                mSocketService.bind(new InetSocketAddress(SocketConfig.SERVER_PORT));
                acceptClient();
            } catch (IOException e) {
                postSocketConnectedStatus(SocketStatusEvent.CONNECTED_FAILED);
                e.printStackTrace();
            }
        }

        private void acceptClient() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Log.d(TAG, "run: ");
                    while (mointor) {
                        try {
                            mSocket = mSocketService.accept();
                            mointor = false;
                            postSocketConnectedStatus(SocketStatusEvent.CONNECTED_SUCCESS);
                            Log.d(TAG, "run: 客户端接收成功");
                        } catch (IOException e) {
                            postSocketConnectedStatus(SocketStatusEvent.CONNECTED_FAILED);
                            mointor = false;
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }

        public Socket getSocket() {
            return mSocket;
        }
        public void setMonitor(boolean mointor){
            this.mointor = mointor;
        }

        //通知Socket 连接状况
        void postSocketConnectedStatus(int status) {
            SocketStatusEvent statusBean = new SocketStatusEvent();
            statusBean.status = status;
            EventBus.getDefault().post(statusBean);
        }
    }

}
